@echo off
setlocal enabledelayedexpansion

echo ================================================
echo MySQL 8.0 Installation for Property Cleaning System
echo ================================================
echo.

echo [1/3] Downloading MySQL 8.0 Community Server...
powershell -Command "
Write-Host 'Downloading MySQL 8.0...' -ForegroundColor Green
$url = 'https://dev.mysql.com/get/Downloads/MySQLInstaller/mysql-installer-community-8.0.35.0.msi'
$output = 'mysql-installer.msi'
if (-not (Test-Path $output)) {
    Invoke-WebRequest -Uri $url -OutFile $output
    Write-Host 'Download complete!' -ForegroundColor Green
} else {
    Write-Host 'Installer already exists' -ForegroundColor Yellow
}
"

echo [2/3] Installing MySQL 8.0...
powershell -Command "
Write-Host 'Installing MySQL...' -ForegroundColor Yellow
Start-Process -Wait -FilePath msiexec.exe -Args '/i mysql-installer.msi /quiet'
Write-Host 'MySQL installation complete!' -ForegroundColor Green
"

echo [3/3] Configuring MySQL for Property Cleaning System...
set "MYSQL_PATH=%PROGRAMFILES%\MySQL\MySQL Server 8.0\bin"
if exist "%MYSQL_PATH%\mysql.exe" (
    echo Adding MySQL to PATH...
    setx PATH "%PATH%;%MYSQL_PATH%" /M
    
    echo Starting MySQL service...
    net start MySQL80
    
    echo Waiting for MySQL to start...
    timeout /t 10 /nobreak >nul
    
    echo Creating database...
    "%MYSQL_PATH%\mysql.exe" -u root -e "CREATE DATABASE IF NOT EXISTS property_cleaning;"
    
    echo Importing schema...
    if exist "database\schema.sql" (
        "%MYSQL_PATH%\mysql.exe" -u root property_cleaning < database\schema.sql
        echo [OK] Database schema imported successfully!
    ) else (
        echo [WARNING] schema.sql not found, please run from project directory
    )
    
    echo Setting up user credentials...
    "%MYSQL_PATH%\mysql.exe" -u root -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root123';"
    "%MYSQL_PATH%\mysql.exe" -u root -e "FLUSH PRIVILEGES;"
    
    echo.
    echo ================================================
    echo MySQL Setup Complete!
    echo ================================================
    echo Database: property_cleaning
    echo Username: root
    echo Password: root123
    echo Port: 3306
    echo Service: MySQL80
    echo.
    echo To test connection:
    echo mysql -u root -p
) else (
    echo [ERROR] MySQL installation failed or path not found
    echo Please run MySQL Installer manually from Start Menu
)

echo.
echo Cleaning up installer...
if exist mysql-installer.msi del mysql-installer.msi

echo.
echo Press any key to continue...
pause